package com.yangl.corejava.thread;

import java.util.concurrent.TimeUnit;

/**
 * Created by yangl on 2017/5/1.
 */
public class ShutdownTest {
    public static void main(String[] args) throws InterruptedException {
       Runner one = new Runner();
       Thread countThread = new Thread(one, "CountThread");
       countThread.start();
        //睡眠1秒，mian线程对CountThread进行中断，使CountThread能够感知中断而结束
        TimeUnit.SECONDS.sleep(1);
        countThread.interrupt();
        Runner two = new Runner();
        countThread = new Thread(two, "CountThread");
        countThread.start();
        //睡眠1秒，mian线程对Runner Two进行取消，使CountThread能够感知on为false而结束
        TimeUnit.SECONDS.sleep(1);
        two.cancel();
    }

    private static class Runner implements Runnable{

        private long i = 0;

        private volatile boolean on = true;

        public void run() {
            while(on && !Thread.currentThread().isInterrupted()){
                i++;
            }
            System.out.println("Count i = " + i);
        }

        public void cancel(){
            on = false;
        }

    }
}
